package info.motteke.kurumi;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;


public class ImageUtil {

    public static void resizeImage(File source, File target, int x, int y, String suffix) {
        try {
            BufferedImage base = ImageIO.read(source);
            int oldWidth = base.getWidth();
            int oldHeight = base.getHeight();
            int newWidth;
            int newHeight;
            double oldScale = (double)base.getWidth() / (double)base.getHeight();
            double newScale = (double)x / (double)y;

            if(Double.compare(oldScale, newScale) < 0){
                // 要求より縦長
                newWidth = (int)(oldWidth * y / (double)oldHeight);
                newHeight = y;
            } else {
                // 要求より横長
                newWidth = x;
                newHeight = (int)(oldHeight * x / (double)oldWidth);
            }

            Image image = base.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
            BufferedImage background = new BufferedImage(x, y, BufferedImage.TYPE_INT_RGB);
            Graphics g = background.getGraphics();
            g.setColor(Color.WHITE);
            g.fillRect(0, 0, x, y);
            g.drawImage(image, (x - newWidth) / 2, (y - newHeight) / 2, newWidth, newHeight, Color.WHITE, null);

            ImageIO.write(background, suffix, target);
        } catch (IOException e) {

        }
    }
}
